import React, { Component,Fragment } from 'react'
import List from './list'
import store from '../../../store/redux-saga'
import { changeIptAction,changeItemAction,setListAction,changeItemSageAction } from '../../../store/redux-saga/actionCreators'
import './list.css'

export default class TodoList extends Component{
    constructor(props){
        super(props);
        this.state = store.getState()
        this.delfun = this.delfun.bind(this)
        this.addHandle = this.addHandle.bind(this)
        this.changeIpt = this.changeIpt.bind(this)
        this.storeChange = this.storeChange.bind(this)
        store.subscribe(this.storeChange)
    }
    render(){
        return (<Fragment>
            <div>
                <label htmlFor="todoTxt">备忘录：</label>
                <input id="todoTxt" 
                    onChange={this.changeIpt} 
                    ref={(input)=>{this.iptVal = input}} 
                    placeholder="please input" 
                    value={this.state.iptVal}
                />
                <button onClick={this.addHandle}>添加</button>
            </div>
            <List 
                data={this.state.list}
                delFun={this.delfun}
            />
        </Fragment>);
    }
    changeIpt(){
        const action = changeIptAction(this.iptVal.value);
        store.dispatch(action);
    }
    addHandle(){
        let list = JSON.parse(JSON.stringify(this.state.list))
        if(this.state.iptVal){
            list.push(this.state.iptVal)
            const action = changeItemAction(list)
            store.dispatch(action)
        }

    }
    delfun(idx){
        let list = JSON.parse(JSON.stringify(this.state.list))
        list.splice(idx,1)
        // const action = changeItemAction(list)
        const action = changeItemSageAction()
        console.log(action)
        store.dispatch(action)
    }
    storeChange(){
        this.setState(store.getState())
    }
    componentDidMount(){
       const action = setListAction();
       store.dispatch(action)
    }
}
